<script lang="ts" setup>
import { ref } from 'vue';
import { isBefore, subDays } from 'date-fns';
import type { FormInstance } from '@arco-design/web-vue/es/form';
import { $fetch } from '@/settings/utils/fetch';
import useNotification from '@/settings/hooks/notification';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';

const props = defineProps({
  id: {
    type: String,
    default: '',
  },
});

const eventType = ref()
const loading = ref(false);
const formData = ref({
  atName: '',
  atUrl: '',
  atTemplate: '',
  buttonText: '',
  jumpUrl: '',
  atType: 1,
  sort: 0,
  times: [] as string[],
  location: '',
});
const formRef = ref<FormInstance>();
const router = useRouter();
const { success } = useNotification();
const { t } = useI18n();
const templates = import.meta.glob('/src/common/components/activity-template/*/index.vue', {
  eager: true,
  import: 'default',
}) as Record<string, any>;

const save = async () => {
  const params: Record<string, any> = {
    atId: props.id,
    atStartTime: formData.value.times?.[0],
    atEndTime: formData.value.times?.[1],
    ...formData.value,
  }

  if (eventType.value === 1) {
    params.atUrl = '';
  }
  else {
    params.atTemplate = 0;
  }

  delete params.times;

  const { isSuccess } = await $fetch(props.id ? '/admin/activity/update' : '/admin/activity/create', {
    method: 'post',
    data: params,
    loadingStatus: loading,
  });

  if (isSuccess) {
    success(t('settings.notification.success'));
    router.push('/operator/event/index');
  }
};

const submit = async () => {
  const res = await formRef.value?.validate();

  if (res) {
    return;
  }

  save();
};

const getDetail = async () => {
  const { isSuccess, data } = await $fetch('/admin/activity/info', {
    data: {
      id: props.id,
    },
    loadingStatus: loading,
  });

  if (isSuccess) {
    eventType.value = data.atUrl ? 2 : 1;
    formData.value = {
      atName: data.atName,
      atUrl: data.atUrl,
      atTemplate: data.atTemplate < 1 ? '' : data.atTemplate,
      buttonText: data.buttonText,
      jumpUrl: data.jumpUrl,
      atType: data.atType,
      sort: data.sort,
      times: [data.atStartTime, data.atEndTime],
      location: data.location,
    };
  }
}

const isCurrentBeforeNow = (current: Date) => {
  const now = new Date();
  return isBefore(current, subDays(now, 1));
};

const init = () => {
  if (props.id) {
    getDetail();
  }
  else {
    eventType.value = 1;
  }
}

init();
</script>

<template>
  <OpenPageSection>
    <OpenGeneralCard>
      <AForm ref="formRef" auto-label-width scroll-to-first-error :model="formData" @submit="submit">
        <AFormItem :label="$t('settings.view.event.edit.colum1')" field="atName" :rules="[{ required: true, message: $t('settings.notification.required') }, { maxLength: 150 }]">
          <AInput v-model="formData.atName" :max-length="150" allow-clear show-word-limit />
        </AFormItem>

        <AFormItem :label="$t('settings.view.event.edit.colum2')">
          <ARadioGroup v-model="eventType">
            <ARadio :value="1">{{ $t('settings.view.event.edit.type1') }}</ARadio>
            <ARadio :value="2">{{ $t('settings.view.event.edit.type2') }}</ARadio>
          </ARadioGroup>
        </AFormItem>

        <AFormItem v-if="eventType === 1" :label="$t('settings.view.event.edit.type1')" field="atTemplate" :rules="[{ required: true, message: $t('settings.notification.required') }]">
          <ARadioGroup v-model="formData.atTemplate">
            <div class="flex">
              <template v-for="item in 3" :key="item">
                <ARadio :value="item">
                  <template #radio="{ checked }">
                    <ASpace direction="vertical" align="center" class="custom-radio-card" :class="{ 'custom-radio-card-checked': checked }">
                      <Component
                        class="mt-16 h-144 w-240 text-14 leading-20"
                        :is="templates[`/src/common/components/activity-template/${item}/index.vue`]"
                        :title="$t('settings.view.event.edit.notice')"
                        v-if="item !== 4 && templates[`/src/common/components/activity-template/${item}/index.vue`]"
                      />
                      <div className="custom-radio-card-mask">
                        <div className="custom-radio-card-mask-dot"></div>
                      </div>
                    </ASpace>
                  </template>
                </ARadio>
              </template>
            </div>
          </ARadioGroup>
        </AFormItem>

        <AFormItem v-if="eventType === 2" :label="$t('settings.view.event.edit.colum3')" field="atUrl" :rules="[{ required: true, message: $t('settings.notification.required') }]" :help="$t('settings.view.event.edit.help')">
          <OpenUpload v-model="formData.atUrl" />
        </AFormItem>

        <AFormItem :label="$t('settings.view.event.edit.colum4')" field="buttonText" :rules="[{ maxLength: 150 }] " :help="$t('settings.view.event.edit.button')">
          <AInput v-model.trim="formData.buttonText" :max-length="150" allow-clear show-word-limit />
        </AFormItem>

        <AFormItem :label="$t('settings.view.event.edit.colum5')" field="jumpUrl" :rules="[{ required: true, message: $t('settings.notification.required') }, { maxLength: 150 }]">
          <AInput v-model.trim="formData.jumpUrl" :max-length="150" allow-clear show-word-limit />
        </AFormItem>

        <AFormItem :label="$t('settings.view.event.edit.colum7')" :rules="[{ required: true, message: $t('settings.notification.required') }]" v-if="!props.id">
          <ARadioGroup v-model="formData.atType">
            <ARadio :value="1">{{ $t('settings.view.operation.edit.status.1') }}</ARadio>
            <ARadio :value="2">{{ $t('settings.view.operation.edit.status.2') }}</ARadio>
          </ARadioGroup>
        </AFormItem>

        <AFormItem :label="$t('settings.view.event.edit.colum8')" field="times" :rules="[{ required: true, message: $t('settings.notification.required') }]" v-if="formData.atType === 1">
          <ARangePicker :disabled-date="(current:any) => isCurrentBeforeNow(current ?? new Date())" show-time v-model="formData.times" />
        </AFormItem>

        <AFormItem :label="$t('settings.view.event.edit.colum9')" field="times" :rules="[{ maxLength: 150 }]">
          <AInput v-model.trim="formData.location" :max-length="150" allow-clear show-word-limit />
        </AFormItem>

        <AFormItem :label="$t('settings.view.event.edit.colum6')" field="sort" :rules="[{ required: true, message: $t('settings.notification.required') }]" class="w-240">
          <AInputNumber v-model="formData.sort" :default-value="0" allow-clear show-word-limit mode="button" />
        </AFormItem>

        <ADivider />

        <AFormItem>
          <ASpace>
            <AButton html-type="submit" type="primary" :loading="loading">{{ $t('settings.action.submit') }}</AButton>
          </ASpace>
        </AFormItem>
      </AForm>
    </OpenGeneralCard>
  </OpenPageSection>
</template>

<style lang="scss" scoped>
.custom-radio-card {
  box-sizing: border-box;
  width: 274px;
  padding: 10px 16px;
  border: 1px solid var(--color-border-2);
  border-radius: 4px;
}

.custom-radio-card-mask {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  width: 14px;
  height: 14px;
  border: 1px solid var(--color-border-2);
  border-radius: 100%;
}

.custom-radio-card-mask-dot {
  width: 8px;
  height: 8px;
  border-radius: 100%;
}

.custom-radio-card-title {
  margin-bottom: 8px;
  color: var(--color-text-1);
  font-weight: bold;
  font-size: 14px;
}

.custom-radio-card:hover,
.custom-radio-card-checked,
.custom-radio-card:hover .custom-radio-card-mask,
.custom-radio-card-checked .custom-radio-card-mask {
  border-color: rgb(var(--primary-6));
}

.custom-radio-card-checked {
  background-color: var(--color-primary-light-1);
}

.custom-radio-card:hover .custom-radio-card-title,
.custom-radio-card-checked .custom-radio-card-title {
  color: rgb(var(--primary-6));
}

.custom-radio-card-checked .custom-radio-card-mask-dot {
  background-color: rgb(var(--primary-6));
}
</style>
